import Vue from 'vue'
export default {
	state: {
		token: '',
		isLogin: false,
		isOnwer: false,
		loginUser: {
			gender: 1,
			nickname: '未登录',
			motto: '点击快速登录~',
			avatar: 'https://lovestatic.jokeo.cn/202106/222.jpg',
		}
	},
	getters: {
		getToken: state => {
			return state.token
		},
		getLoginUser: state => {
			return state.loginUser
		},
		getLoginUserId: state => {
			return state.loginUser.id
		},
		getIsLogin: state => {
			return state.isLogin
		}
	},
	mutations: {
		modifyToken(state, payload) {
			state.token = payload;
			uni.setStorageSync('token', payload)
		},
		modifyLoginUser(state, payload) {
			state.isLogin = true;
			state.loginUser = payload;
			uni.setStorageSync('userInfo', payload)
		}
	},
	actions: {
		updateLoginUser(context, userInfo) {
			context.commit('modifyLoginUser', userInfo);
			context.commit('modifyLoveStartId', userInfo.loveId);
		},
		//实现登录和注册功能
		login(context) {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: function(res) {
						if (res.code) {
							let param = {
								appid: Vue.prototype.appid,
								code: res.code,
								nickname: '小猪',
								avatar: 'https://lovestatic.jokeo.cn/pig.jpeg'
							};
							Vue.prototype.$u.api.wechatRegister(param).then(res => {
								console.info(res);
								resolve("login执行完毕");
								context.commit('modifyToken', res.token);
								context.dispatch('updateLoginUser', res.loginUser);
							});
						} else {
							Vue.prototype.$u.toast("登录失败");
							reject("获取code失败");
						}
					}
				});
			})
		},

		// 1.获取微信用户信息---废弃不能用了
		getWxUserInfo() {
			wx.getUserProfile({
				desc: '用于完善您的登录信息',
				success: res => {
					// console.log(res);
					this.wxlogin(res.userInfo);
				},
				fail: res => {
					console.log(res);
				}
			});
		},
		//2.获取code用于注册登录
		wxlogin() {
			uni.login({
				provider: 'weixin',
				success: function(res) {
					if (res.code) {
						this.wechatRegistered(res.code);
					} else {
						console.log('获取登录code失败!!');
					}
				}
			});
		},
		//3.注册登录
		wechatRegistered(code) {
			let param = {
				appid: this.appid,
				code: code,
				nickname: '小猪',
				avatar: 'https://lovestatic.jokeo.cn/pig.jpeg'
			};
			this.$u.api.wechatRegister(param).then(res => {
				console.info(res);
				context.commit('modifyToken', res.token);
				context.commit('modifyLoginUser', res.loginUser);
			});
		},
	}
}